//
//  CXHTradPlusNativeAdapter.m
//  CXHAdSDK-TradPlus
//
//  Created by 陈坤 on 2023/9/20.
//

#import "CXHTradPlusNativeAdapter.h"
#import <TradPlusAds/TradPlusAdWaterfallItem.h>
#import <CXHAdSDK-Core/CXHAdSDK.h>
#import <CXHAdSDK-Core/CXHAdSDKNativeAd.h>
#import <CXHAdSDK-Kit/CXHUtilsKit.h>
#import <CXHAdSDK-Adapter/CXHAdapterNativeAdViewDelegate.h>
#import <CXHAdSDK-Adapter/CXHAdapterNativeAdData.h>

@interface CXHTradPlusNativeAdapter ()<CXHAdSDKNativeAdDelegate>{
    UIView<CXHAdapterNativeAdViewDelegate> *_adView;
}

@property (nonatomic, strong) CXHAdSDKNativeAd *nativeAd;

@property (nonatomic, assign) BOOL isInit;

@property (nonatomic, assign) BOOL isC2SBidding;

@end

@implementation CXHTradPlusNativeAdapter

//根据event实现相关流程
- (BOOL)extraActWithEvent:(NSString *)event info:(NSDictionary *)config
{
    if([event isEqualToString:@"C2SBidding"]){
        //从三方SDK获取价格
        [self getECPMC2SBidding];
    } else if([event isEqualToString:@"LoadAdC2SBidding"]) {
        //竞价成功后的加载流程
        [self loadAdC2SBidding];
    } else if ([event isEqualToString:@"C2SLoss"]) {
        NSString *topPirce = config[@"topPirce_cny"];
        [self.nativeAd sendLossNotice:[topPirce integerValue]];
    } else {
        return NO;
    }
    return YES;
}

- (void)getECPMC2SBidding {
//    [self initSDK:self.waterfallItem.config];
    [self startC2SBidding];
}

//通过三方API获取ECPM
- (void)startC2SBidding {
    self.isC2SBidding = YES;
    NSString *posid = self.waterfallItem.config[@"posid"];
    
    if (kCXHStringIsEmpty(posid)) {
//        NSDictionary *dic = @{@"error": @"get bid price failed"};
        [self AdLoadFailWithError:[NSError errorWithDomain:@"get bid price failed" code:-1 userInfo:nil]];
        return;
    }
    
    self.nativeAd.posId = posid;
    
    [self loadAdWithWaterfallItem:self.waterfallItem];
}

- (void)loadAdC2SBidding {
    if ([self isReady]) {
        [self.nativeAd sendWinNotice:self.nativeAd.getBidPrice];
        [self AdLoadFinsh];
    }else{
        NSError *loadError = [NSError errorWithDomain:@"load native ad failed" code:404 userInfo:@{NSLocalizedDescriptionKey : @"C2S native ad not ready"}];
        [self AdLoadFailWithError:loadError];
    }
}

- (CXHAdSDKNativeAd *)nativeAd{
    if (_nativeAd == nil) {
        _nativeAd = [[CXHAdSDKNativeAd alloc] init];
        _nativeAd.delegate = self;
    }
    return _nativeAd;
}

//初始化自定义平台，设置平台参数（海外平台的隐私设置）加载广告
- (void)loadAdWithWaterfallItem:(TradPlusAdWaterfallItem *)item{
    [self initSDK:item.config];
    //通过 item.config 获取后台配置信息
    NSString *posid = item.config[@"posid"];
    
    if (kCXHStringIsEmpty(posid)) {
        [self AdConfigError];
        return;
    }
//    NSLog(@"========%@", item.nativeRootViewController);
    if (item.nativeRootViewController) {
        self.nativeAd.controller = item.nativeRootViewController;
    }
    self.nativeAd.posId = posid;
    [self.nativeAd load:1];
}

- (void)initSDK:(NSDictionary *)config {
    if (self.isInit) {
        return;
    }
    self.isInit = YES;
    NSString *domain = [config CXH_objectOrNilForKey:@"domain"];
    if (kCXHStringIsEmpty(domain)) {
        domain = @"";
    }
    
    NSString *appid = [config CXH_objectOrNilForKey:@"appid"];
    if (!kCXHStringIsEmpty(appid)) {
        [CXHAdSDK initWithAppId:appid requestDomain:domain completionBlock:^(NSError * _Nullable error) {
            if (error) {
                [self AdConfigError];
            }
        }];
    }
}

//此方法用于返回是否过期状态
- (BOOL)isReady
{
    return (_adView != nil);
}

//自渲染类型，在渲染完成后在此方法中进行三方注册操作
//模版类型，不要实现此方法
- (UIView *)endRender:(NSDictionary *)viewInfo clickView:(NSArray *)array
{
    UIView *view = viewInfo[kTPRendererAdView];
    if (_adView == nil) {
        return nil;
    }
    _adView.frame = view.bounds;
    if (self.rootViewController) {
        [_adView cxh_setRootViewController:self.rootViewController];
    }
    [_adView cxh_registViews:@[_adView,view]];
    [view addSubview:_adView];
    return nil;
}


#pragma mark - CXHAdSDKNativeAdDelegate
/**
 信息流原生广告请求成功

 @param nativeAd 广告实例
 @param adViewArray 广告模板集合
 */
- (void)CXH_nativeAdSucessToLoad:(CXHAdSDKNativeAd *)nativeAd
                     adViewArray:(NSArray<__kindof UIView<CXHAdapterNativeAdViewDelegate> *> *)adViewArray{
    UIView<CXHAdapterNativeAdViewDelegate> *adview = [adViewArray firstObject];
    _adView = adview;
    CXHAdapterNativeAdData *adData = [adview cxh_nativeAdData];
    //新建 TradPlusAdRes 并进行资源绑定
    TradPlusAdRes *res = [[TradPlusAdRes alloc] init];
    res.title = adData.title;
    res.body = adData.desc;
    
    res.mediaImageURL = adData.imageUrl;
    res.imageURLList = @[adData.imageUrl];
    
    if(adData.iconImageUrl != nil)
    {
        res.iconImageURL = adData.iconImageUrl;
    }
    //模版类型只需要绑定 res.adView
    //完成绑定，设置Res。用于TP SDK的原生界面渲染
    self.waterfallItem.adRes = res;
    
    if (self.isC2SBidding) {
        NSInteger price = self.nativeAd.getBidPrice;
        if (price <= 0) {
            NSDictionary *dic = @{@"error": @"get bid price failed"};
            [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFail" info:dic];
            return;
        }
        //通过接口向TradPlusSDK回传ecpm和三方版本号
        float f = price/100.00;
        NSString *ecpmStr = [NSString stringWithFormat:@"%.2f", f];
        NSDictionary *dic = @{@"ecpm":ecpmStr,@"version":[CXHAdSDK getSDKVersion]};
        [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFinish" info:dic];
    }else{
        [self AdLoadFinsh];
    }
}

/**
 信息流广告请求失败

 @param nativeAd 广告实例
 @param error 请求错误描述
 */
- (void)CXH_nativeAdFailToLoad:(CXHAdSDKNativeAd *)nativeAd
                         error:(NSError *)error{
    
    if(self.isC2SBidding)
    {
        NSDictionary *dic = @{@"error": @"c2s bidding load failed"};
        [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFail" info:dic];
    }
    else
    {
        [self AdLoadFailWithError:error];
    }
}

/**
 信息流广告被点击

 @param nativeAd 广告模板
 */
- (void)CXH_nativeAdClicked:(CXHAdSDKNativeAd *)nativeAd
                     adView:(__kindof UIView<CXHAdapterNativeAdViewDelegate> *)adView loadingPageURL:(NSString *)loadingPageURL{
    [self AdClick];
}

/**
 信息流广告被关闭
 
 @param nativeAd 广告模板
 */
- (void)CXH_nativeAdClose:(CXHAdSDKNativeAd *)nativeAd
                   adView:(__kindof UIView<CXHAdapterNativeAdViewDelegate> *)adView{
    [self AdClose];
}

/**
 信息流广告被展示
 
 @param nativeAd 广告实例
 */
- (void)CXH_nativeAdExposure:(CXHAdSDKNativeAd *)nativeAd
                      adView:(__kindof UIView<CXHAdapterNativeAdViewDelegate> *)adView{
    [self AdShow];
}

/**
 信息流广告落地页被关闭
 
 @param nativeAd 广告实例
 */
- (void)CXH_nativeAdCloseLandingPage:(CXHAdSDKNativeAd *)nativeAd
                              adView:(__kindof UIView<CXHAdapterNativeAdViewDelegate> *)adView{
    
}

@end
